package com.fruit.dao;

import java.sql.*;
import java.util.List;

public class BaseDAO {

    private static String url = "jdbc:mysql://localhost:3306/1715b?characterEncoding=UTF-8";
    private static String username = "root";
    private static String password = "";
    private static String driverClass = "com.mysql.jdbc.Driver";

    private Connection connection = null;
    private PreparedStatement preparedStatement = null;
    private ResultSet resultSet = null;

    public void openConnection() {
        try {
            Class.forName(driverClass);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void closeAll() {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public ResultSet excuteQuery(String sql, List<Object> params) throws Exception {
        if (connection == null || connection.isClosed()) {
            openConnection();
        }
        preparedStatement = connection.prepareStatement(sql);
        if (params != null && params.size() > 0) {
            for (int i = 0; i < params.size(); i++) {
                preparedStatement.setObject(i + 1, params.get(i));
            }
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    public int excuteUpdate(String sql, List<Object> params) throws Exception {
        if (connection == null || connection.isClosed()) {
            openConnection();
        }
        preparedStatement = connection.prepareStatement(sql);
        if (params != null && params.size() > 0) {
            for (int i = 0; i < params.size(); i++) {
                preparedStatement.setObject(i + 1, params.get(i));
            }
        }
        return preparedStatement.executeUpdate();
    }
}
